import { ref, onMounted, onBeforeUnmount, type Ref } from 'vue';

/**
 * 让任意元素精准感知自己是否处于 sticky 状态
 * @param targetRef  需要监听 sticky 的 DOM 引用
 * @param rootMargin 触发边界微调，默认 '-1px 0 0 0'
 * @returns  响应式布尔值，true 表示已 sticky
 */
export function useSticky(
  targetRef: Ref<HTMLElement | undefined>,
  rootMargin = '-1px 0px 0px 0px'
) {
  const isSticky = ref(false);
  let observer: IntersectionObserver | null = null;
  let sentinel: HTMLElement | null = null;

  onMounted(() => {
    if (!targetRef.value) return;

    /* 1. 创建 0 高哨兵，插入到目标元素之前 */
    sentinel = document.createElement('div');
    sentinel.style.height = '0px';
    sentinel.style.width = '100%';
    targetRef.value.parentElement!.insertBefore(sentinel, targetRef.value);

    /* 2. 监听哨兵相交状态 */
    observer = new IntersectionObserver(
      ([entry]) => {
        isSticky.value = !entry.isIntersecting;
      },
      { rootMargin, threshold: [0] }
    );
    observer.observe(sentinel!);
  });

  onBeforeUnmount(() => {
    if (observer && sentinel) {
      observer.unobserve(sentinel);
      sentinel.remove();
      observer = null;
      sentinel = null;
    }
  });

  return isSticky;
}
